<script>
import { generateCode } from '@/api/activationCode';
import Button from 'primevue/button';
import { useToast } from 'primevue/usetoast';
import InputText from 'primevue/inputtext';
import InputNumber from 'primevue/inputnumber';
import DataView from 'primevue/dataview';
import Chip from 'primevue/chip';
import Steps from 'primevue/steps';
import { listQuestionBank } from '@/api/questionBank';
import { useRouter } from 'vue-router';
import Tooltip from 'primevue/tooltip';
import PickList from 'primevue/picklist';
import Tag from 'primevue/tag';
import IconField from 'primevue/iconfield';
import ScrollPanel from 'primevue/scrollpanel';
import Fieldset from 'primevue/fieldset';

export default {
    components: {
        Button,
        InputText,
        InputNumber,
        DataView,
        Chip,
        Steps,
        PickList,
        Tag,
        IconField,
        ScrollPanel,
        Fieldset
    },
    directives: {
        tooltip: Tooltip
    },
    data() {
        return {
            activeStep: 0,
            steps: [
                { label: '选择题库', icon: 'pi pi-book' },
                { label: '确认信息', icon: 'pi pi-check-circle' },
                { label: '生成结果', icon: 'pi pi-list' }
            ],
            allQuestionBanks: [], // 存储所有题库数据
            questionBanks: [],
            filteredBanks: [],
            generateForm: {
                questionBankIds: [],
                count: 1,
                duration: 30
            },
            generatedCodes: [],
            submitted: false,
            loading: false,
            generatingCodes: false,
            searchQuery: '',
            selectedBank: null,
            searchTimeout: null,
            pickListValue: [[], []],
            groupedCodes: []
        };
    },
    mounted() {
        this.loadQuestionBanks();
    },
    watch: {
        'generateForm.questionBankId': {
            handler(newVal) {
                if (newVal) {
                    this.selectedBank = this.filteredBanks.find((bank) => bank.id === newVal) || null;
                } else {
                    this.selectedBank = null;
                }
            },
            immediate: true
        }
    },
    methods: {
        onStepChange(e) {
            if (e.index > this.activeStep) {
                if (e.index === 1 && !this.generateForm.questionBankIds) {
                    this.$toast.add({
                        severity: 'warn',
                        summary: '提示',
                        detail: '请先选择一个题库',
                        life: 3000
                    });
                    return;
                }
                if (e.index === 2 && this.generatedCodes.length === 0) {
                    this.$toast.add({
                        severity: 'warn',
                        summary: '提示',
                        detail: '请先生成激活码',
                        life: 3000
                    });
                    return;
                }
            }
            this.activeStep = e.index;
        },

        nextStep() {
            if (this.activeStep < this.steps.length - 1) {
                this.activeStep++;
            }
        },

        prevStep() {
            if (this.activeStep > 0) {
                this.activeStep--;
            }
        },

        generateAndNext() {
            this.submitted = true;
            if (!this.generateForm.questionBankIds || !this.generateForm.count) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '请完成所有必填项',
                    life: 3000
                });
                return;
            }
            this.generateActivationCode().then(() => {
                if (this.generatedCodes.length > 0) {
                    this.nextStep();
                }
            });
        },

        resetForm() {
            this.activeStep = 0;
            this.generateForm.questionBankIds = null;
            this.generateForm.count = 1;
            this.selectedBank = null;
            this.generatedCodes = [];
            this.submitted = false;
        },

        async loadQuestionBanks() {
            this.loading = true;
            try {
                const response = await listQuestionBank({
                    // 不再使用分页参数，一次性加载所有数据
                    name: this.searchQuery || null,
                    language: null
                });

                if (response.code === 200) {
                    const newBanks = response.data || [];
                    // 过滤掉已经在目标列表中的题库
                    const filteredNewBanks = newBanks.filter((bank) => !this.pickListValue[1].some((target) => target.id === bank.id));

                    this.allQuestionBanks = filteredNewBanks; // 更新所有题库数据
                    this.pickListValue[0] = filteredNewBanks; // 更新可选题库列表
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载题库数据',
                        life: 3000
                    });
                }
            } catch (error) {
                console.error('加载题库失败:', error);
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载题库数据',
                    life: 3000
                });
            } finally {
                this.loading = false;
            }
        },

        onSearch() {
            clearTimeout(this.searchTimeout);
            this.searchTimeout = setTimeout(() => {
                // 本地搜索，不再请求接口
                const query = this.searchQuery.trim().toLowerCase();
                this.pickListValue[0] = this.allQuestionBanks.filter((bank) => bank.name.toLowerCase().includes(query));
            }, 300);
        },

        async generateActivationCode() {
            this.submitted = true;

            // this.mockGeneratedData();
            // return Promise.resolve();

            if (!this.generateForm.questionBankIds || !this.generateForm.count) {
                return Promise.reject('缺少必填项');
            }

            try {
                this.generatingCodes = true;
                const response = await generateCode(this.generateForm);

                if (response.code === 200) {
                    this.$toast.add({
                        severity: 'success',
                        summary: '成功',
                        detail: '激活码生成成功',
                        life: 3000
                    });

                    const rawData = response.data || [];
                    this.generatedCodes = rawData.flatMap((item) => item.activationCodes);

                    this.groupedCodes = rawData.map((item) => {
                        const matchedBank = this.pickListValue[1].find((bank) => bank.id === item.questionBankId);
                        return {
                            questionBankId: item.questionBankId,
                            bankInfo: matchedBank || { name: `题库 ${item.questionBankId}`, cover: null },
                            activationCodes: item.activationCodes || []
                        };
                    });

                    return Promise.resolve();
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '失败',
                        detail: response.message || '生成激活码失败',
                        life: 3000
                    });
                    return Promise.reject(response.message);
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '错误',
                    detail: '生成激活码时出错',
                    life: 3000
                });
                console.error('生成激活码失败:', error);

                if (process.env.NODE_ENV === 'development') {
                    this.mockGeneratedData();
                    return Promise.resolve();
                }

                return Promise.reject(error);
            } finally {
                this.generatingCodes = false;
            }
        },

        mockGeneratedData() {
            this.groupedCodes = this.pickListValue[1].map((bank) => {
                return {
                    questionBankId: bank.id,
                    bankInfo: bank,
                    activationCodes: Array.from({ length: this.generateForm.count }, () => `AC-${bank.id}-${Math.random().toString(36).substring(2, 10).toUpperCase()}`)
                };
            });
            this.generatedCodes = this.groupedCodes.flatMap((group) => group.activationCodes);

            console.log(this.groupedCodes);
        },

        copyAllCodes() {
            const text = this.generatedCodes.join('\n');
            navigator.clipboard
                .writeText(text)
                .then(() => {
                    this.$toast.add({
                        severity: 'success',
                        summary: '复制成功',
                        detail: '所有激活码已复制到剪贴板',
                        life: 3000
                    });
                })
                .catch((err) => {
                    console.error('复制失败:', err);
                    this.$toast.add({
                        severity: 'error',
                        summary: '复制失败',
                        detail: '无法复制到剪贴板',
                        life: 3000
                    });
                });
        },

        copySingleCode(code) {
            navigator.clipboard
                .writeText(code)
                .then(() => {
                    this.$toast.add({
                        severity: 'success',
                        summary: '复制成功',
                        detail: '激活码已复制到剪贴板',
                        life: 3000
                    });
                })
                .catch((err) => {
                    console.error('复制失败:', err);
                    this.$toast.add({
                        severity: 'error',
                        summary: '复制失败',
                        detail: '无法复制到剪贴板',
                        life: 3000
                    });
                });
        },

        copyBankCodes(codes) {
            const text = codes.join('\n');
            navigator.clipboard
                .writeText(text)
                .then(() => {
                    this.$toast.add({
                        severity: 'success',
                        summary: '复制成功',
                        detail: '此题库的激活码已复制到剪贴板',
                        life: 3000
                    });
                })
                .catch((err) => {
                    console.error('复制失败:', err);
                    this.$toast.add({
                        severity: 'error',
                        summary: '复制失败',
                        detail: '无法复制到剪贴板',
                        life: 3000
                    });
                });
        },

        goToListPage() {
            this.router.push('/activationCode');
        },

        onPickListChange(e) {
            console.log('PickList change:', e);
            this.pickListValue = e;

            if (e[1] && e[1].length > 0) {
                const selectedBanks = e[1];
                this.generateForm.questionBankIds = selectedBanks.map((bank) => bank.id);
                this.selectedBank = selectedBanks;
                console.log('选择的题库ID:', this.generateForm.questionBankIds);
            } else {
                this.generateForm.questionBankIds = null;
                this.selectedBank = null;
            }
        },

        viewUsageHistory(code) {
            this.router.push({
                path: '/activationCode/usage',
                query: { code }
            });
        }
    },
    setup() {
        const toast = useToast();
        const router = useRouter();

        return {
            toast,
            router
        };
    }
};
</script>

<template>
    <div class="md:w-3/4 mx-auto">
        <div class="card">
            <Toast />
            <Toolbar class="mb-4">
                <template #start>
                    <Button label="返回列表" icon="pi pi-arrow-left" severity="secondary" @click="goToListPage" class="p-button-rounded" />
                </template>
            </Toolbar>

            <Steps :model="steps" :readonly="false" :activeStep="activeStep" @step-change="onStepChange" />
            <div class="">
                <div v-if="activeStep === 0" class=" mt-8 shadow-2 border-round-lg fade-in">
                    <h5 class="mb-4"><i class="pi pi-book mr-2 text-primary"></i>选择要生成激活码的题库</h5>

                    <div class="surface-border border-round">
                        <PickList v-model="pickListValue" :showSourceControls="false" :showTargetControls="false" list-style="max-height: 20rem" @update:modelValue="onPickListChange" :metaKeySelection="false" breakpoint="1400px" :loading="loading">
                            <template #sourceheader>
                                <div class="w-full">
                                    <div class="flex align-items-center gap-2 mb-2">
                                        <Tag class="text-primary" icon="pi pi-book" :rounded="true" severity="success" value="Success">可选题库 </Tag>
                                    </div>
                                    <div class="p-inputgroup w-full min-w-full mb-2">
                                        <IconField class="rounded">
                                            <InputIcon class="pi pi-search rounded" />
                                            <InputText class="w-full min-w-full rounded" v-model="searchQuery" @input="onSearch" placeholder="Search" />
                                        </IconField>
                                    </div>
                                </div>
                            </template>
                            <template #targetheader>
                                <div class="flex align-items-center gap-2">
                                    <Tag size="large" class="text-primary" icon="pi pi-check-circle" :rounded="true" severity="info" value="Success">已选题库 </Tag>
                                </div>
                            </template>
                            <template #item="slotProps">
                                <div class="flex align-items-center w-full gap-3 p-1">
<!--                              下面Chip :label下面的内容原来是这个      :image="slotProps.item.cover || '/path/to/default-cover.jpg'"-->
                                    <Chip
                                        :label="slotProps.item.name"

                                        class="w-full"
                                        imageClass="w-3rem h-3rem border-circle shadow-1"
                                        @error="$event.target.src = '/path/to/default-cover.jpg'"
                                    />
                                </div>
                            </template>
                        </PickList>
                    </div>

                    <div class="flex justify-end">
                        <Button label="下一步" icon="pi pi-arrow-right" iconPos="right" @click="nextStep" :disabled="!generateForm.questionBankIds" class="p-button-raised" />
                    </div>
                </div>

                <div v-if="activeStep === 1" class=" p-4 shadow-2 border-round-lg fade-in">
                    <h5 class="mb-4"><i class="pi pi-check-circle mr-2 text-primary"></i>确认生成激活码</h5>

                    <div class="p-4 surface-card border-round shadow-1 mb-4">
                        <div class="flex align-items-center mb-2">
                            <Tag size="large" class="text-primary" :rounded="true" severity="info">已选题库 ({{ pickListValue[1].length }}) </Tag>
                        </div>
                        <div class="card border">
                            <ScrollPanel style="width: 100%; height: 200px" class="border-1 surface-border border-round">
                                <div class="p-2">
                                    <div v-for="(bank, index) in pickListValue[1]" :key="bank.id" class="p-2 flex align-items-center border-bottom-1 surface-border mb-2" :class="{ 'surface-ground': index % 2 === 0 }">
                                        <Chip :label="bank.name"  class="w-full" imageClass="w-3rem h-3rem border-circle shadow-1" @error="$event.target.src = '/path/to/default-cover.jpg'" />
                                    </div>
                                </div>
                            </ScrollPanel>
                        </div>
                    </div>

                    <div class="field mb-4">
                        <label for="count" class="block font-bold mb-2 text-900">生成数量</label>
                        <InputNumber
                            id="count"
                            v-model="generateForm.count"
                            required="true"
                            :min="1"
                            :max="100"
                            class=""
                            showButtons
                            buttonLayout="horizontal"
                            decrementButtonClass="p-button-secondary"
                            incrementButtonClass="p-button-secondary"
                            incrementButtonIcon="pi pi-plus"
                            decrementButtonIcon="pi pi-minus"
                        />
                        <small v-if="submitted && !generateForm.count" class="p-error">数量是必须的</small>
                    </div>
                    <div class="field mb-4">
                        <label for="duration" class="block font-bold mb-2 text-900">有效期(Day)</label>
                        <InputNumber
                            id="duration"
                            v-model="generateForm.duration"
                            required="true"
                            :min="1"
                            showButtons
                            buttonLayout="horizontal"
                            decrementButtonClass="p-button-secondary"
                            incrementButtonClass="p-button-secondary"
                            incrementButtonIcon="pi pi-plus"
                            decrementButtonIcon="pi pi-minus"
                        />
                        <small v-if="submitted && !generateForm.duration" class="p-error">有效期是必须的</small>
                    </div>

                    <div class="flex justify-between mt-4">
                        <Button label="上一步" icon="pi pi-arrow-left" class="p-button-outlined" @click="prevStep" />
                        <Button label="生成激活码" icon="pi pi-check" @click="generateAndNext" :loading="generatingCodes" class="p-button-raised" />
                    </div>
                </div>

                <div v-if="activeStep === 2" class="card p-4 shadow-2 border-round-lg fade-in">
                    <h5 class="mb-4"><i class="pi pi-list mr-2 text-primary"></i>激活码生成结果</h5>

                    <div v-for="(group, gIndex) in groupedCodes" :key="`group-${gIndex}`" class="mb-3">
                        <Fieldset>
                            <template #legend>
                                <div class="flex align-items-center gap-2">
                                    <div>
                                        <div class="text-lg font-medium">{{ group.bankInfo.name }}</div>
                                        <div class="text-sm text-500">生成 {{ group.activationCodes.length }} 个激活码</div>
                                    </div>
                                    <Button icon="pi pi-copy" text rounded size="small" @click="copyBankCodes(group.activationCodes)" v-tooltip.top="'复制此题库全部激活码'" class="ml-auto" />
                                </div>
                            </template>

                            <div class="activation-codes-list border-1 surface-border border-round">
                                <div class="p-2 bg-gray-50 border-bottom-1 surface-border">
                                    <div class="flex justify-content-between align-items-center">
                                        <div class="text-sm text-500">有效期: {{ generateForm.duration }}天</div>
                                    </div>
                                </div>
                                <ScrollPanel style="max-height: 200px">
                                    <div class="grid">
                                        <div v-for="(code, index) in group.activationCodes" :key="`code-${index}`" class="col-12 md:col-6 lg:col-4 xl:col-3">
                                            <div class="p-2 border-bottom-1 surface-border flex justify-content-between align-items-center" :class="{ 'surface-ground': index % 2 === 0 }">
                                                <div class="flex align-items-center gap-2">
                                                    <code class="text-sm">{{ code }}</code>
                                                    <Button icon="pi pi-copy" text rounded severity="secondary" size="small" @click="copySingleCode(code)" v-tooltip.top="'复制此激活码'" />
                                                    <Button icon="pi pi-history" text rounded severity="info" size="small" @click="viewUsageHistory(code)" v-tooltip.top="'查看使用记录'" />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </ScrollPanel>
                            </div>
                        </Fieldset>
                    </div>

                    <div class="flex justify-between mt-4">
                        <Button label="重新生成" icon="pi pi-refresh" severity="secondary" @click="prevStep" />
                        <Button label="返回列表" icon="pi pi-arrow-right" iconPos="right" severity="success" @click="goToListPage" class="p-button-raised" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
:deep(.p-fieldset) {
    margin-bottom: 1.5rem;
}

:deep(.p-fieldset-legend) {
    padding: 0.75rem 1.25rem;
    width: auto;
    max-width: 100%;
}

.activation-codes-list {
    background-color: white;
    overflow: hidden;
}

code {
    font-family: monospace;
    background-color: var(--surface-100);
    padding: 0.2rem 0.4rem;
    border-radius: 3px;
    word-break: break-all;
}
</style>
